/* @flow */

import config from '../config'
import VNode, { createEmptyVNode } from './vnode'
import { createComponent } from './create-component'
import { traverse } from '../observer/traverse'

import {
  warn,
  isDef,
  isUndef,
  isTrue,
  isObject,
  isPrimitive,
  resolveAsset
} from '../util/index'

import {
  normalizeChildren,
  simpleNormalizeChildren
} from './helpers/index'

const SIMPLE_NORMALIZE = 1
const ALWAYS_NORMALIZE = 2

/**
 * 将render函数转换为vnode
 * @param {*} context 上下文，如: Vue
 * @param {*} tag  标签名，如: div
 * @param {*} data attr属性，如: statusClass: 'className'
 * @param {*} children 当前的子类，vnode对象
 * @param {*} normalizationType 
 * @param {*} alwaysNormalize  表示解析的类型，如果子类全部是普通Dom,这里是undefined,如果存components, render函数里面调用当前函数时传递1
 */
export function createElement (
  context: Component,
  tag: any,
  data: any, 
  children: any,
  normalizationType: any,
  alwaysNormalize: boolean
): VNode | Array<VNode> {

  /**
   * 这里只是纠正一下格式，如果解析到的一个标签如果没有属性
   * 那么其children就会跑到data参数里面
   */
  if (Array.isArray(data) || isPrimitive(data)) {
    normalizationType = children
    children = data
    data = undefined
  }
  if (isTrue(alwaysNormalize)) {
    normalizationType = ALWAYS_NORMALIZE
  }
  return _createElement(context, tag, data, children, normalizationType)
}

export function _createElement (
  context: Component,
  tag?: string | Class<Component> | Function | Object,
  data?: VNodeData,
  children?: any,
  normalizationType?: number
): VNode | Array<VNode> {

  //如果data为可响应式的数据，抛出警告
  if (isDef(data) && isDef((data: any).__ob__)) {
    process.env.NODE_ENV !== 'production' && warn(
      `Avoid using observed data object as vnode data: ${JSON.stringify(data)}\n` +
      'Always create fresh vnode data objects in each render!',
      context
    )
    return createEmptyVNode()
  }
  // object syntax in v-bind
  if (isDef(data) && isDef(data.is)) {
    tag = data.is
  }
  if (!tag) {
    // in case of component :is set to falsy value
    return createEmptyVNode()
  }

  // support single function children as default scoped slot
  if (Array.isArray(children) &&
    typeof children[0] === 'function'
  ) {
    data = data || {}
    data.scopedSlots = { default: children[0] }
    children.length = 0
  }

  if (normalizationType === ALWAYS_NORMALIZE) { //2
    //如果是传值匿名插槽normalizationType再AST就会传递2
    children = normalizeChildren(children)
  } else if (normalizationType === SIMPLE_NORMALIZE) { //1
    //如果是for循环生成的子累，那么children本身就会是一个数组，因此这里就是将数组扁平为一维
    children = simpleNormalizeChildren(children)
  }

  let vnode, ns

  if (typeof tag === 'string') {
    let Ctor
    
    //一些特殊的标签,如svg
    ns = (context.$vnode && context.$vnode.ns) || config.getTagNamespace(tag)

  
    if (config.isReservedTag(tag)) { //内置html标签走此路线

      //这里走正常初始化路线，创建vnode
      vnode = new VNode(
        config.parsePlatformTagName(tag), data, children,
        undefined, undefined, context
      )

      //resolveAsset方法就是从第一个参数对象里面获取到第二个参数key的值，然后从值里面再获取第三个参数key的值
      //这里Ctors 是得到对应的组件对象(没有处理过的)
    } else if ((!data || !data.pre) && isDef(Ctor = resolveAsset(context.$options, 'components', tag))) {  //自定义组件路线
      /**
       * component时会走次路线
       * Ctor components里面注册的组件对象
       * data 当前组件的attr属性
       * context 上下文 Vue
       * children 当前的组件的子类
       * tag 当前组件的标签名
       */
      vnode = createComponent(Ctor, data, context, children, tag)
    } else {    //不知道什么类型的组件
      // unknown or unlisted namespaced elements
      // check at runtime because it may get assigned a namespace when its
      // parent normalizes children
      vnode = new VNode(
        tag, data, children,
        undefined, undefined, context
      )
    }

  } else {
    // direct component options / constructor
    vnode = createComponent(tag, data, context, children)
  }


  if (Array.isArray(vnode)) {
    return vnode
  } else if (isDef(vnode)) {
    //普通Dom和component都会走次路线返回
    if (isDef(ns)){
      applyNS(vnode, ns)
    }
    if (isDef(data)){
      //data就是attr属性，这里注册动态属性，静态属性跳过不处理
      registerDeepBindings(data)
    }
    return vnode
  } else {
    return createEmptyVNode()
  }
}

function applyNS (vnode, ns, force) {
  vnode.ns = ns
  if (vnode.tag === 'foreignObject') {
    // use default namespace inside foreignObject
    ns = undefined
    force = true
  }
  if (isDef(vnode.children)) {
    for (let i = 0, l = vnode.children.length; i < l; i++) {
      const child = vnode.children[i]
      if (isDef(child.tag) && (
        isUndef(child.ns) || (isTrue(force) && child.tag !== 'svg'))) {
        applyNS(child, ns, force)
      }
    }
  }
}

// ref #5318
// necessary to ensure parent re-render when deep bindings like :style and
// :class are used on slot nodes
function registerDeepBindings (data) {
  if (isObject(data.style)) {
    traverse(data.style)
  }
  if (isObject(data.class)) {
    traverse(data.class)
  }
}
